/*
 * @Description: 
 * @Date: 2023-03-28 18:51:28
 * @LastEditTime: 2023-04-17 20:26:05
 * @Author: Black
 * @FilePath: \store_admin\src\store\index.js
 */
import { createStore } from 'vuex'
import { getinfo, login } from '~/api/manager'
import { setToken, removeToken } from '~/composables/auth'

// 创建一个新的 store 实例
const store = createStore({
	state() {
		return {
			// 用户信息
			user: {},
			// 侧边菜单栏的状态
			asideWidth: "250px",
			// 侧边栏菜单的数据
			menus: [],
			ruleNames: []
		}
	},
	// 定义修改状态的方法：只允许同步操作，不允许异步操作
	mutations: {
		// 记录用户信息
		SET_USERINFO(state, user) {
			state.user = user
		},

		// 侧边菜单栏的展开和收缩
		handleAsideWidth(state) {
			state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px"
		},

		SET_MENUS(state, menus) {
			state.menus = menus
		},

		SET_RULENAMES(state, ruleNames) {
			state.ruleNames = ruleNames
		}

	},
	// 类似于mutation, 为异步操作而生
	actions: {
		// 登录功能封装
		login({ commit }, { username, password }) {
			return new Promise((resolve, reject) => {
				login(username, password).then(res => {
					setToken(res.token)
					resolve(res)
				}).catch(err => reject(err))
			})
		},
		// 获取当前用户相关信息
		getinfo({ commit }) {
			return new Promise((resolve, reject) => {
				getinfo().then(res => {
					commit("SET_USERINFO", res)
					commit("SET_MENUS", res.menus)
					commit("SET_RULENAMES", res.ruleNames)
					resolve(res)
				}).catch(err => reject(err))
			})
		},
		// 退出登录
		logout({ commit }) {
			// 移除cookies里面的token
			removeToken()
			// 清除当前用户状态 vuex
			commit("SET_USERINFO", {})
		}
	}
})

export default store